﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<!-- 搜索区域 - 头部 -->
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="false">
			<el-row :gutter="15">
				<el-col :xs="24" :sm="12" :md="8" :lg="6" class="mb15">
					<el-form-item ref="Code_FormItem" prop="Code" label="岗位编号">
						<el-input v-model="searchData.Code" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="8" :lg="6" class="mb15">
					<el-form-item ref="Name_FormItem" prop="Name" label="岗位名称">
						<el-input v-model="searchData.Name" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="8" :lg="6" class="mb15">
					<el-form-item ref="GroupId_FormItem" prop="GroupId">
						<template #label>
							<WtmLabelTooltip label="所属部门" tooltip="关联的部门" />
						</template>
						<el-cascader
							:options="stateData.AllSysGroups"
							:props="{ checkStrictly: true, emitPath: false, label: 'Text', value: 'Value', children: 'Children' }"
							clearable
							filterable
							class="w100"
							v-model="searchData.GroupId"
						/>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="8" :lg="6" class="mb15">
					<el-form-item ref="SelectedRolesIds_FormItem" prop="SelectedRolesIds" label="角色">
						<el-input v-model="searchData.SelectedRolesIds" multiple :data="stateData.AllFrameworkRoles" clearable></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</WtmSearcher>

		<!-- 工具栏 -->
		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysJobPosition/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysJobPosition/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysJobPosition/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysJobPosition/SysJobPositionExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<!-- 主内容区域 - 左右布局 -->
		<div class="main-content-layout">
			<!-- 左侧部门树 -->
			<div class="left-panel" v-if="searchBar">
				<WtmDeptTree ref="deptTreeRef" title="筛选部门" @node-click="handleDeptNodeClick" />
			</div>

			<!-- 右侧表格 -->
			<div class="right-panel">
				<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
					<template #operation>
						<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
							<template v-slot="scope">
								<div class="operation-container">
									<WtmButton
										v-auth="'/api/SysJobPosition/Edit'"
										:is-text="true"
										icon="fa fa-pencil-square"
										type="warning"
										:button-text="$t('message._system.common.vm.edit')"
										@click="OnEditRowClick(scope.row)"
									/>
									<WtmButton
										v-if="scope.row.CanApprove == 'true'"
										:is-text="true"
										icon="-o"
										type="warning"
										button-text="审批"
										@click="OnDetailsRowClick(scope.row)"
									/>
									<WtmButton
										v-else
										v-auth="'/api/SysJobPosition/{id}'"
										:is-text="true"
										icon="fa fa-info-circle"
										type="info"
										:button-text="$t('message._system.common.vm.detail')"
										@click="OnDetailsRowClick(scope.row)"
									/>
									<WtmButton
										v-auth="'/api/SysJobPosition/BatchDelete'"
										icon="fa fa-trash"
										type="danger"
										:button-text="$t('message._system.common.vm.delete')"
										:confirm="$t('message._system.common.vm.deletetip')"
										:is-text="true"
										@click="onDelete(scope.row)"
									/>
								</div>
							</template>
						</el-table-column>
					</template>
				</WtmTable>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts" name="岗位管理;true;HengTong.Areas._Admin.Controllers;SysJobPosition">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysJobPositionApi as api } from '/@/views/_admin/sysjobposition/api';
import { ISysJobPositionView, ISysJobPositionQuery } from '/@/views/_admin/sysjobposition/api/interface';
import other from '/@/utils/other';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const deptTreeRef = ref();
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysJobPositionQuery;
		/** 所属部门 */
		GroupId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		GroupId: '',
	}
);

const stateData = reactive({
	AllSysGroups: [] as any[],
	AllFrameworkRoles: [] as any[],
});

const searchData = ref<ISysJobPositionQuery>({});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		{ title: '岗位编号', key: 'Code', type: 'text', isCheck: true },
		{ title: '岗位名称', key: 'Name', type: 'text', isCheck: true },
		{ title: '岗位薪资', key: 'Salary', type: 'text', isCheck: true },
		{ title: '岗位描述', key: 'Description', type: 'text', isCheck: true },
		{ title: '所属部门', key: 'GroupName', type: 'text', isCheck: true },
		{ title: '角色', key: 'RolesName', type: 'text', isCheck: true },
		{ title: '是否管理', key: 'IsManager', type: 'switch', isCheck: true },
		{ title: '排序', key: 'Order', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};

// 处理部门树节点点击
const handleDeptNodeClick = (node: any) => {
	// 如果点击的是根节点或者Value为空，则清空部门筛选
	if (!node.Value || node.Value === 'all') {
		searchData.value.GroupId = '';
	} else {
		searchData.value.GroupId = node.Value;
	}
	getTableData();
};

const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData, '70%');
};

const OnEditRowClick = (row: ISysJobPositionView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData, '70%');
};

const OnDetailsRowClick = (row: ISysJobPositionView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData, '70%');
};

// 删除
const onDelete = (row: ISysJobPositionView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysJobPositionView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};

// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;

	// 设置GroupId到搜索条件
	if (props.GroupId) {
		searchData.value.GroupId = props.GroupId;
	}

	const promises: Promise<any>[] = [
		other.getSelectList('/api/common/GetGroups?auth=false', [], false).then((x) => {
			stateData.AllSysGroups = x;
		}),

		other.getSelectList('/api/SysJobPosition/GetFrameworkRoles', [], false).then((x) => {
			stateData.AllFrameworkRoles = x;
		}),

		getTableData(),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
